package constant

import (
	"github.com/lab-online/internal/shared/code"
	"github.com/lab-online/pkg/errors"
	"github.com/lab-online/pkg/gen"
	"github.com/lab-online/pkg/resp"
)

const (
	baseReqErrorCode       = resp.CodeBadRequest + domainCode
	codeUserNotFound       = baseReqErrorCode + 0
	codeUserAlreadyExists  = baseReqErrorCode + 1
	codeUserNotMatch       = baseReqErrorCode + 2
	codePasswordNotMatch   = baseReqErrorCode + 3
	codeNoPermissionCreate = baseReqErrorCode + 4
	codeNoPermissionPatch  = baseReqErrorCode + 5
	codeStudentArrayEmpty  = baseReqErrorCode + 6
	codeStudentDuplicate   = baseReqErrorCode + 7

	baseServerErrorCode    = resp.CodeServerError + domainCode
	codePasswordHashError  = baseServerErrorCode + 0
	codePasswordResetError = baseServerErrorCode + 1
	codeTokenGenError      = baseServerErrorCode + 2

	dbUnknownError = code.DatabaseUnknownError
	dbUserNotFound = code.DatabaseUserNotFound
)

var (
	RESTErrUserNotFound       = errors.NewRESTError(400, codeUserNotFound, "用户不存在")
	RESTErrUserAlreadyExists  = errors.NewRESTError(400, codeUserAlreadyExists, "用户已存在")
	RESTErrUserNotMatch       = errors.NewRESTError(400, codeUserNotMatch, "用户名/密码错误")
	RESTErrPasswordNotMatch   = errors.NewRESTError(400, codePasswordNotMatch, "密码错误")
	RESTErrNoPermissionCreate = errors.NewRESTError(403, codeNoPermissionCreate, "无权限创建高权限的用户")
	RESTErrNoPermissionPatch  = errors.NewRESTError(403, codeNoPermissionPatch, "无权限修改")
	RESTErrStudentArrayEmpty  = errors.NewRESTError(400, codeStudentArrayEmpty, "学生数组长度为 0")
	RESTErrStudentDuplicate   = errors.NewRESTError(400, codeStudentDuplicate, "学生学号重复")

	RESTErrPasswordHashError = errors.NewRESTError(500, codePasswordHashError, "服务端密码加密错误")
	RESTErrTokenGenError     = errors.NewRESTError(500, codeTokenGenError, "服务端token生成错误")

	DBErrUnknown      = errors.NewDBError(dbUnknownError, "user 表未定义错误")
	DBErrUserNotFound = errors.NewDBError(dbUserNotFound, "未找到指定用户")
)

func ErrCodeMap() gen.CodeMap {
	return gen.ParseCodeMapFromErrors(gen.ErrorMap{
		"Register": {
			RESTErrUserAlreadyExists,
			RESTErrPasswordHashError,
			RESTErrTokenGenError,
			RESTErrNoPermissionCreate,

			DBErrUnknown,
		},
		"Login": {
			RESTErrUserNotMatch,
			RESTErrPasswordHashError,
			RESTErrTokenGenError,

			DBErrUnknown,
		},
		"GetProfile": {
			DBErrUnknown,
		},
		"DeleteUser": {
			RESTErrUserNotFound,

			DBErrUnknown,
		},
		"UpdateUser": {
			RESTErrUserNotFound,
			RESTErrNoPermissionPatch,

			DBErrUnknown,
		},
		"UpdatePassword": {
			RESTErrUserNotFound,
			RESTErrNoPermissionPatch,
			RESTErrPasswordNotMatch,
			RESTErrPasswordHashError,

			DBErrUnknown,
		},
		"SearchUser": {
			RESTErrUserNotFound,

			DBErrUnknown,
		},
		"RefreshToken": {
			RESTErrUserNotFound,
			RESTErrTokenGenError,
			DBErrUnknown,
		},
	})
}
